package com.wx.plugin.sms.holder;

import com.wx.plugin.context.ThreadContext;
import com.wx.plugin.sms.api.SMSApi;
import com.wx.plugin.util.DateUtil;
import com.wx.plugin.util.DigestUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Random;

/**
 * <p></p>
 *
 * @author  yangz
 * @date    2016/11/7
 * @version latest
 */
@Component
@Data
public class SMSHolder {

    public final static String SMS_SUCCESS = "0000";
    public final static String TIMESTAMP_FORMAT = "yyyyMMddHHmmss";
    public final static String REPONSE_TYPE = "JSON";

    @Autowired
    private SMSApi smsApi;

    @Value("${sms.account.sid}")
    private String accountSid;

    @Value("${sms.account.token}")
    private String accountToken;

    @Value("${sms.account.app}")
    private String accountApp;

    public void sendYZM(String to){
        String timestamp = DateUtil.format(new Date(), TIMESTAMP_FORMAT);
        String sig = DigestUtil.md5(accountSid + accountToken + timestamp);
        Random rnd = new Random();
        int num = rnd.nextInt(89999) + 10000;
        String yzm = String.valueOf(num);
        String smsContent = "【" + accountApp + "】" + "您的验证码是"+yzm+"，30分钟输入有效，我是不会告诉别人的。";
        String s = smsApi.sendSMS(accountSid, smsContent, to, timestamp, sig, REPONSE_TYPE);
        ThreadContext.getRequest().getSession().setAttribute(ThreadContext.KEY_YZM, yzm);
    }
}
